package com.th.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.th.common.domain.SysFile;
import com.th.common.exception.BaseServiceException;
import com.th.common.response.ExceptionResultData;
import com.th.config.file.FileProperties;
import com.th.mapper.SysFileMapper;
import com.th.service.SysFileService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.util.Objects;

/**
 * @Author tuhang
 * @PackageName nswcy-crowdsource-client-server
 * @Package com.th.service.impl
 * @Date 2023/6/8 18:24
 * @Version 1.0
 */
@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService{


    @Resource
    private FileProperties fileProperties;
    @Override
    public String createFile(String path, byte[] content) {
        if (this.getBaseMapper().selectCount(SysFile::getId,path) > 0) {
            throw new BaseServiceException(ExceptionResultData.FILE_PATH_EXISTS);
        }
        // 保存到数据库
        SysFile file = new SysFile();
        file.setId(path);
        file.setType(FileTypeUtil.getType(new ByteArrayInputStream(content)));
        file.setContent(content);
        this.getBaseMapper().insert(file);
        // 拼接路径返回
        return fileProperties.getBasePath() + path;
    }

    @Override
    public void deleteFile(String id) {
        if (Objects.nonNull(this.getBaseMapper().selectById(id))) {
            this.getBaseMapper().deleteById(id);
        }
    }


    @Override
    public SysFile getFile(String path) {
        return  this.getBaseMapper().selectById(path);
    }
}
